package com.avertymaroc.users;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.avertymaroc.app.MainActivity;
import com.avertymaroc.app.R;
import com.avertymaroc.library.C;
import com.avertymaroc.library.HttpManager;
import com.avertymaroc.library.ImageLoader;
import com.avertymaroc.library.SessionManager;

public class Articles extends SherlockActivity{
	
	private static final String TAG_IMAGE		= "image";
	private static final String TAG_TOTAL		= "total";
	private static final String TAG_SLUG		= "slug";
	private static final String TAG_TITRE		= "titre";
	private static final String TAG_ARTICLES	="articles";
	private static final int ARTICES_PAR_PAGE	= 9;
	
	private ImageLoader imageLoader;
	private ArrayList<HashMap<String, Object>> data;
	private GridView gridView;
	private int currentPage = 0  , total = 0 , loadedPages = 0 , totalPages;
	private GridAdapter mAdapter;
	private ImageButton suivant , precedent;
	private ProgressBar bar;
	private ImageButton logOut;
	private ImageButton homePage;
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setTheme(MainActivity.THEME);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.articles_liste);
		init();
	
	
	}
	
	
	
	
	private void init(){
		
		data = new ArrayList<HashMap<String,Object>>();
		gridView = (GridView) findViewById(R.id.grid_view);
		imageLoader = new ImageLoader(this);
		imageLoader.setStub_id(R.drawable.averty_log);
		suivant = (ImageButton) findViewById(R.id.btn_suivant);
		precedent = (ImageButton) findViewById(R.id.btn_precedent);
		initActionBarButtons();
		
		Listener l = new Listener();
		suivant.setOnClickListener(l);
		precedent.setOnClickListener(l);
		
		HttpManager articles = new HttpManager(Articles.this) {
			
			@Override
			protected void onPostExecute(String file_url) {
				this.getpDialog().dismiss();
				ArrayList<HashMap<String, Object>> d = new ArrayList<HashMap<String,Object>>();
				
				JSONObject res = getResult();
				try {
					if(loadedPages == 0){
						total = res.getInt(TAG_TOTAL);
						totalPages =(int) Math.ceil( (double)total/ARTICES_PAR_PAGE);
					}
					
					JSONArray aricleList = res.getJSONArray(TAG_ARTICLES);

					for(int i = 0 ; i< aricleList.length() ; i++){
						JSONObject o = aricleList.getJSONObject(i);
						HashMap<String, Object> map = new HashMap<String, Object>();
						map.put(TAG_IMAGE, o.getString(TAG_IMAGE));
						map.put(TAG_SLUG , o.getString(TAG_SLUG));
						map.put(TAG_TITRE , o.getString(TAG_TITRE));
						d.add(map);
						data.add(map);
						
						
					}
					
					loadedPages++;
					mAdapter = new GridAdapter(Articles.this, d);
					gridView.setAdapter(mAdapter);
					currentPage = loadedPages;
					if(loadedPages < totalPages)
						suivant.setVisibility(View.VISIBLE);
					
				} catch (JSONException e) {
					Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
				}
				
			}
		};
		articles.setUrl(C.site_url("mobile/articles/index/"+(loadedPages+1)))
		.execute();
		
		
		gridView.setOnItemClickListener(l);
		
		
	}
	
	
	
	
private void loadRemoteData(){
	
	
	if(data.size() < total){
			HttpManager articles = new HttpManager(Articles.this) {
				
				@Override
				protected void onPostExecute(String file_url) {
					this.getpDialog().dismiss();
					ArrayList<HashMap<String, Object>> d = new ArrayList<HashMap<String,Object>>();
					
					JSONObject res = getResult();
					try {
						
						JSONArray aricleList = res.getJSONArray(TAG_ARTICLES);
		
						for(int i = 0 ; i< aricleList.length() ; i++){
							JSONObject o = aricleList.getJSONObject(i);
							HashMap<String, Object> map = new HashMap<String, Object>();
							map.put(TAG_IMAGE, o.getString(TAG_IMAGE));
							map.put(TAG_SLUG , o.getString(TAG_SLUG));
							map.put(TAG_TITRE , o.getString(TAG_TITRE));
							d.add(map);
							data.add(map);
							
						}
						
						loadedPages++;
						mAdapter = new GridAdapter(Articles.this, d);
						gridView.setAdapter(mAdapter);
						currentPage ++;
						
						// initialisation des button suivant et precedent 
						initButtons();
						
						
					} catch (JSONException e) {
						Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
					}
					
				}
			};
			articles.setUrl(C.site_url("mobile/articles/index/"+(loadedPages+1)))
			.execute();
	}
}

	class GridAdapter extends BaseAdapter{
		
		 private Context mContext;
		    private ArrayList<HashMap<String, Object>> data;
		    private  LayoutInflater inflater=null;
		  
		    // Constructor
		    public GridAdapter(Context c , ArrayList<HashMap<String, Object>> d){
		        mContext = c;
		        data = d;
		        inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		    }
		 
		    @Override
		    public int getCount() {
		        return data.size();
		    }
		 
		    @Override
		    public Object getItem(int position) {
		        return position;
		    }
		 
		    @Override
		    public long getItemId(int position) {
		        return position;
		    }
		 
		    @Override
		    public View getView(int position, View convertView, ViewGroup parent) {
		    	View vi=convertView;
		    	if(convertView==null)
		            	vi = inflater.inflate(R.layout.grid_article, null);
		            
		    	
		    	HashMap<String, Object> d = data.get(position);

		    		ImageView image = (ImageView) vi.findViewById(R.id.article_img);
		        	TextView titre = (TextView)vi.findViewById(R.id.titre);
		        	titre.setText((String)d.get(TAG_TITRE));
		        	imageLoader.DisplayImage(C.base_url("upload/articles/"+d.get(TAG_IMAGE)), image);
		    	
		        return vi;
		    }
		    
		    
		 
	}
	

	
	class Listener implements OnClickListener, OnItemClickListener{

		@Override
		public void onClick(View v) {
			
			if(v == suivant){
				nextPage();
			}
			if(v == precedent){
				prevPage();
			}
	
		}

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			
			String url = C.site_url("mobile/articles/one/")+data.get(position).get(TAG_SLUG)+"?email="+(new SessionManager(getApplicationContext()).getUserDetails().getEmail());
			Uri uri = Uri.parse(url);
			Intent intent = new Intent(Intent.ACTION_VIEW, uri);
			startActivity(intent);
			
		}
		
	}
	
	
	private void nextPage(){
		
		if(currentPage == loadedPages){
			loadRemoteData();
		}else
		{
			currentPage++;
			loadLocalData();
		}
		
		
	}
	
	
	
	private void prevPage(){
		if(currentPage > 1){
			currentPage--;
			loadLocalData();
		}
	
	}
	
	
	private void loadLocalData() {
		
			ArrayList<HashMap<String, Object>> d = new  ArrayList<HashMap<String,Object>>();
			int debut = (currentPage - 1) * ARTICES_PAR_PAGE;
			
			for(int i = 0 ; i < 9 ;i++){
				if( i + debut<data.size() )
					d.add(data.get(i + debut));
				else
					break;
			}
			mAdapter = new GridAdapter(this, d);
			gridView.setAdapter(mAdapter);
			initButtons();
			
		}
	
	private void initButtons()
	{
		
		if(currentPage < loadedPages)
			suivant.setVisibility(Button.VISIBLE);
		else
			if(loadedPages < totalPages)
				suivant.setVisibility(Button.VISIBLE);
			else
				suivant.setVisibility(Button.INVISIBLE);
		
		if(currentPage == 1)
			precedent.setVisibility(Button.INVISIBLE);
		else
			precedent.setVisibility(Button.VISIBLE);
	}
	private void initActionBarButtons(){
		 
		 logOut = (ImageButton) findViewById(R.id.ab_right_button);
		 homePage = (ImageButton) findViewById(R.id.ab_left_button);
		 
		 logOut.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				new SessionManager(getApplicationContext()).logoutUser();
				
			}
		});
		 homePage.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
			
				finish();
				
			}
		});
		 
	}
}
